<template>
    <AdminSkeleton>
        <template #header>
            <div class="params-form">
                <el-form label-width="auto" :model="paramsForm">
                    <el-form-item label="班组:" size="small">
                        <el-config-provider :value-on-clear="''" :empty-values="['', undefined, null]">
                            <el-select v-model="paramsForm.pg" clearable placeholder="请选择班组" size="small"
                                style="width: 150px" @visible-change="changePg">
                                <el-option v-for="item in useStore.pgs" :label="item.PGNAME" :value="item.PERSONGROUP"
                                    :key="item.PERSONGROUP" />
                            </el-select>
                        </el-config-provider>
                    </el-form-item>
                    <el-form-item label="姓名:" size="small">
                        <el-input v-model="paramsForm.username" />
                    </el-form-item>
                    <el-form-item label="是否到期:" size="small">
                        <el-checkbox v-model="paramsForm.isExpired" size="small" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" size="small" @click="getDatas(paramsForm)"
                            :loading="loading">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </template>
        <template #control>
            <Control :batchIsShow="batchIsShow" :downloadBoxShow="downloadBoxShow" :permObj="permObj"
                @addClick="editDatas('add', {})" @showDownload="showDownloadBox"
                @downloadExcelPaging="downloadExcelPaging(newDatasArr, 'contentTable', '人员配置信息')"
                @downloadExcelAll="downloadExcelAll(datasArr, '人员配置信息')" @batchToggleShow="batchEdit"
                @batchDel="editSubmit('batchDel', selectRows)" @batchUpload="batchUpload"></Control>
            <Paging :dataLength="datasLength" :countPage="countPage" :btnDisabledObj="btnDisabledObj"
                v-model:firstPage="firstPage" v-model:pageSize="pageSize" @toNext="nextPage(firstPage)"
                @toLast="lastPage(firstPage)" @toFirst="toFirstPage" @toEnd="toEndPage" @toSpecify="toSpecifyPage"
                @changePsize="changePageSize"></Paging>
        </template>
        <template #content>
            <el-table :data="newDatasArr" style="width: 100%" v-loading="loading"
                @selection-change="handleSelectionChange" id="contentTable">
                <el-table-column type="selection" width="50" v-if="selectShow" />
                <el-table-column prop="ID" label="ID" width="80" />
                <el-table-column prop="PERSONID" label="人员号" width="80" />
                <el-table-column prop="REALNAME" label="姓名" width="80" />
                <el-table-column prop="LB_PTYPE" label="类型" width="60" />
                <el-table-column prop="VD" label="类型描述" width="80" />
                <el-table-column prop="LBNUM" label="劳保编码" width="110" />
                <el-table-column prop="LSD" label="劳保描述" width="220" />
                <el-table-column prop="SERVICE_CYCLE" label="使用周期" width="80" />
                <el-table-column prop="QUANTITY" label="数量" width="60" />
                <el-table-column prop="LAST_REDATE" label="上次发放日期" width="120">
                    <template #default="{ row }">
                        {{ dateFormat(row.LAST_REDATE) }}
                    </template>
                </el-table-column>
                <el-table-column prop="NEXT_REDATE" label="下次发放日期" width="120">
                    <template #default="{ row }">
                        {{ dateFormat(row.NEXT_REDATE) }}
                    </template>
                </el-table-column>
                <el-table-column prop="REMARK" label="备注" width="120" />
                <el-table-column prop="PERSONGROUP" label="人员组" width="100" />
                <el-table-column prop="PGNAME" label="班组名称" width="130" />
                <el-table-column prop="CREATEDATE" label="创建时间" width="120" />
                <el-table-column fixed="right" label="Operations" min-width="180" v-perm="permObj.update">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="editDatas('update', row)" title="编辑"
                            v-perm="permObj.update">
                            <el-icon>
                                <Edit />
                            </el-icon>
                        </el-button>
                        <el-button type="warning" size="small" @click="editDatas('copy', row)" title="复制"
                            v-perm="permObj.add">
                            <el-icon>
                                <CopyDocument />
                            </el-icon>
                        </el-button>
                        <el-button type="danger" size="small" class="del" title="删除" @click="editSubmit('delete', row)"
                            v-perm="permObj.delete">
                            <el-icon>
                                <DeleteFilled />
                            </el-icon>
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </template>
    </AdminSkeleton>
    <Drawer ref="drawerRef" :title="title" :size="size" @submit="editSubmit(submitType, editForm)"
        @cancel-submit="resetForm">
        <el-form :model="editForm" ref="updateFormRef" :rules="rules">
            <el-form-item label="ID" :label-width="formLabelWidth">
                <el-input v-model="editForm.ID" autocomplete="off" disabled />
            </el-form-item>
            <el-form-item label="人员号" :label-width="formLabelWidth" prop="PERSONID">
                <el-input v-model="editForm.PERSONID" autocomplete="off" />
            </el-form-item>
            <el-form-item label="姓名" :label-width="formLabelWidth" v-show="submitType !== 'add'">
                <el-input v-model="editForm.REALNAME" autocomplete="off"  disabled/>
            </el-form-item>
            <el-form-item label="类型" :label-width="formLabelWidth" prop="LB_PTYPE">
                <el-config-provider :value-on-clear="''" :empty-values="['', undefined, null]">
                    <el-select v-model="editForm.LB_PTYPE" clearable placeholder="请选择类型" style="width: 150px"
                        @visible-change="changePtype">
                        <el-option v-for="item in lbPtypeArr" :label="item.DESCRIPTION" :value="item.VALUE"
                            :key="item.VALUE" />
                    </el-select>
                </el-config-provider>
            </el-form-item>
            <el-form-item label="劳保编码" :label-width="formLabelWidth" prop="LBNUM">
                <el-input v-model="editForm.LBNUM" autocomplete="off" />
            </el-form-item>
            <el-form-item label="发放周期" :label-width="formLabelWidth" prop="SERVICE_CYCLE">
                <el-input v-model="editForm.SERVICE_CYCLE" autocomplete="off" />
            </el-form-item>
            <el-form-item label="数量" :label-width="formLabelWidth" prop="QUANTITY">
                <el-input v-model="editForm.QUANTITY" autocomplete="off" />
            </el-form-item>
            <el-form-item label="上次发放日期" :label-width="formLabelWidth" prop="LAST_REDATE">
                <el-date-picker v-model="editForm.LAST_REDATE" type="date" placeholder="请选择日期" format="YYYY/MM/DD"
                    value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="下次发放日期" :label-width="formLabelWidth" prop="NEXT_REDATE">
                <el-date-picker v-model="editForm.NEXT_REDATE" type="date" placeholder="请选择日期" format="YYYY/MM/DD"
                    value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="备注" :label-width="formLabelWidth" prop="REMARK">
                <el-input v-model="editForm.REMARK" autocomplete="off" />
            </el-form-item>
            <el-form-item label="班组" :label-width="formLabelWidth" prop="PERSONGROUP">
                <el-config-provider :value-on-clear="''" :empty-values="['', undefined, null]">
                    <el-select v-model="editForm.PERSONGROUP" clearable placeholder="请选择班组" style="width: 150px"
                        @visible-change="changePg">
                        <el-option v-for="item in useStore.pgs" :label="item.PGNAME" :value="item.PERSONGROUP"
                            :key="item.PERSONGROUP" />
                    </el-select>
                </el-config-provider>
            </el-form-item>
        </el-form>
    </Drawer>
    <Dialog ref="dialogRef" :uploadKeys="uploadKeys" @uploadFile="uploadFile" @closeDialog="closeDialog"
        @batchUpdate="editSubmit('batchUpdate', uploadTable)" @batchAdd="editSubmit('batchAdd', uploadTable)"
        @downloadTemplate="downloadTemplate('upload-table', '标签值信息导入模板')">
        <el-table :data="uploadTable" style="width: 100%" ref="dialogTableRef" id="upload-table">
            <!-- <el-table-column type="selection" width="50" v-if="selectShow"/> -->
            <el-table-column fixed prop="ID" label="ID" width="80" />
            <el-table-column prop="PERSONID" label="人员号" width="80" />
            <el-table-column prop="LB_PTYPE" label="类型" width="80" />
            <el-table-column prop="LBNUM" label="劳保编码" width="110" />
            <el-table-column prop="SERVICE_CYCLE" label="发放周期" width="80" />
            <el-table-column prop="QUANTITY" label="数量" width="80" />
            <el-table-column prop="LAST_REDATE" label="上次发放日期" width="120" />
            <el-table-column prop="NEXT_REDATE" label="下次发放日期" width="120" />
            <el-table-column prop="REMARK" label="备注" width="120" />
            <el-table-column prop="PERSONGROUP" label="班组" width="100" />
        </el-table>
    </Dialog>
</template>

<script setup>
import { ref, reactive } from 'vue'
import AdminSkeleton from '@/components/AdminSkeleton.vue';
import Paging from '@/components/Paging.vue'
import Control from '@/components/Control.vue'
import Dialog from '@/components/Dialog.vue'
import Drawer from '@/components/Drawer.vue'
import { getLbListInfo, editLbListInfo, editManyLbListInfo } from '@/utils/lpsApi/lb_list'
import { getLbPersonConfigInfo, editLbPersonConfigInfo, editManyLbPersonConfigInfo } from '@/utils/lpsApi/lb_personConfig'
import { getLbValuesInfo } from '@/utils/lpsApi/lb_values'
import { paging } from '@/utils/paging'
import { exportClickFromTableId, exportClickFromDatas } from '@/utils/downloadExcel'
import { objCopy } from '@/utils/objCopy'
import { msgOpen } from '@/utils/msg'
import { confirm, confirmBatch } from '@/utils/confirm'
import { lpsStore } from '@/stores/lpsStore';
import { getPg } from '@/utils/adminApi/usrs'
import { mainStore } from '@/stores/store'
import { dateFormat } from '@/utils/dateFormat'

const useLpsStore = lpsStore()
const useStore = mainStore()
// console.log(useLpsStore)

//权限对象--用于控制按钮显示
const componentName = 'Lb_personConfig'
const permObj = {
    add: { name: componentName, type: 'add' },
    update: { name: componentName, type: 'update' },
    delete: { name: componentName, type: 'delete' }
}


//#region 查询***********************************************************************************************************************
const {
    datasArr,
    datasLength,
    firstPage,
    pageSize,
    countPage,
    newDatasArr,
    btnDisabledObj,
    pagingPreprocessing,
    nextPage,
    lastPage,
    toFirstPage,
    toEndPage,
    toSpecifyPage,
    changePageSize
} = paging() //分页


//查询参数表单对象
const paramsForm = reactive({
    pg: [],
    username: "",
    isExpired: true
})

//获取班组信息
const changePg = async () => {
    if (!useStore.pgs.length) {
        let pgs = await getPg()
        useStore.setPgs(pgs.datas.pgs)
    }
}

// loading状态
let loading = ref(false);

//获取标签值列表
const getDatas = async (params) => {
    // console.log(params)
    loading.value = true;
    const res = await getLbPersonConfigInfo(params)
    // console.log(res)
    pagingPreprocessing(res.resDatas.result)
    loading.value = false;
}
//#endregion********************************************************************************************************




//#region 编辑信息***************************************************************************************************
let title = ref("")
let size = ref("40%")
let formLabelWidth = ref("110")

//编辑用户信息
let drawerRef = ref(null) //组件ref
let oldLbValue = reactive({
    ID: '',
    PERSONID: '',
    REALNAME: '',
    LB_PTYPE: '',
    LBNUM: '',
    SERVICE_CYCLE: '',
    QUANTITY: '',
    LAST_REDATE: '',
    NEXT_REDATE: '',
    REMARK: '',
    PERSONGROUP: '',
})
let editForm = reactive({
    ID: '',
    PERSONID: '',
    REALNAME: '',
    LB_PTYPE: '',
    LBNUM: '',
    SERVICE_CYCLE: '',
    QUANTITY: '',
    LAST_REDATE: '',
    NEXT_REDATE: '',
    REMARK: '',
    PERSONGROUP: '',
})
//提交类型
let submitType = ref('')
//表单验证ref
let updateFormRef = ref(null)
//输入框验证规则
let rules = reactive({
    PERSONID: [
        { required: true, message: '请输入人员编码', trigger: 'blur' }
    ],
    LB_PTYPE: [
        { required: true, message: '请输入类型', trigger: 'blur' }
    ],
    LBNUM: [
        { required: true, message: '请输入物资编码', trigger: 'blur' }
    ],
    SERVICE_CYCLE: [
        { required: true, message: '请输入发放周期', trigger: 'blur' }
    ],
    QUANTITY: [
        { required: true, message: '请输入数量', trigger: 'blur' }
    ],
    LAST_REDATE: [
        { required: true, message: '请输入上次发放日期', trigger: 'blur' }
    ],
    NEXT_REDATE: [
        { required: true, message: '请输入下次发放日期', trigger: 'blur' }
    ],
    // REMARK: [
    //     { required: true, message: '请输入备注', trigger: 'blur' }
    // ],
    PERSONGROUP: [
        { required: true, message: '请输入班组', trigger: 'blur' }
    ],
})

//人员类型
let lbPtypeArr = ref([])

const changePtype = async () => {
    if(!useLpsStore.lbValInfo.length){
        let res = await getLbValuesInfo()
        if(res.status){          
            useLpsStore.setLbValInfo(res.resDatas.result)
            lbPtypeArr.value = useLpsStore.lbValInfo.filter(item=>item.CUST_TYPE === "LB_PTYPE")
        }
    }else{
         lbPtypeArr.value = useLpsStore.lbValInfo.filter(item=>item.CUST_TYPE === "LB_PTYPE")
    } 
}

//重置表单
const resetForm = () => {
    if (submitType.value === 'update' || submitType.value === 'copy') {
        editForm = objCopy(oldLbValue, editForm)
    } else if (submitType.value === 'add') {
        editForm = reactive({
            ID: '',
            PERSONID: '',
            REALNAME: '',
            LB_PTYPE: '',
            LBNUM: '',
            SERVICE_CYCLE: '',
            QUANTITY: '',
            LAST_REDATE: '',
            NEXT_REDATE: '',
            REMARK: '',
            PERSONGROUP: '',
        })
    }
}

/**
 * 处理单个设备编辑、删除
 * @param type 操作类型，add：新增，update：编辑，del：删除
 * @param row 
 */
const editDatas = (type, row) => {
    // console.log(type)
    // console.log(row)
    submitType.value = type
    if (type === 'update') {
        drawerRef.value.open()
        title.value = "编辑"
        editForm = row
        editForm.LAST_REDATE = dateFormat(row.LAST_REDATE)
        editForm.NEXT_REDATE = dateFormat(row.NEXT_REDATE)
        //存储未修改前用户信息
        oldLbValue = objCopy(row, oldLbValue)
    }
    if (type === 'add') {
        drawerRef.value.open()
        title.value = "新增"
        resetForm()
    }
    if (type === "copy") {
        drawerRef.value.open()
        title.value = "复制"
        editForm = objCopy(row, editForm)
        editForm.ID = ""
        editForm.DESCRIPTION += "_副本"
        editForm.LAST_REDATE = dateFormat(row.LAST_REDATE)
        editForm.NEXT_REDATE = dateFormat(row.NEXT_REDATE)
    }
}
//#endregion********************************************************************************************************




//#region 批量处理***************************************************************************************************
let batchIsShow = ref(false) //展示批量上传、批量删除状态
let selectShow = ref(false) //展示批量勾选状态
let selectRows = ref([]) //选中的设备行数据
let dialogRef = ref(null) //组件ref
let uploadKeys = ref([
    "ID",
    "PERSONID",
    "LB_PTYPE",
    "LBNUM",
    "SERVICE_CYCLE",
    "QUANTITY",
    "LAST_REDATE",
    "NEXT_REDATE",
    "REMARK",
    "PERSONGROUP",
]) //上传的字段

const batchEdit = () => {
    if (newDatasArr.value.length) selectShow.value = !selectShow.value
    batchIsShow.value = !batchIsShow.value
}

/**
 * 表格选中行数据变化时触发的方法
 * @param val 选中的设备行数据
 */
const handleSelectionChange = (val) => {
    selectRows.value = val
}

//批量上传
let uploadTable = ref([])
const batchUpload = () => {
    // console.log('batchUpload');
    dialogRef.value.open()
}

//关闭
const closeDialog = () => {
    uploadTable = ref([])
    dialogRef.value.close()
}

//接收子组件传递的excel数据，渲染至界面
let dialogTableRef = ref(null)
const uploadFile = (e) => {
    // console.log(e.value)            
    uploadTable = e.value
}

//下载
let downloadBoxShow = ref(false) //展示下载框状态
const showDownloadBox = () => {
    downloadBoxShow.value = !downloadBoxShow.value
}
/** 
 * 下载当前页
 * @param {Array} data 导出的数据数组对象
 * @param {String} tableId table标签的ID
 * @param {String} fileName 需要命名的文件名
 */
const downloadExcelPaging = (data, tableId, fileName) => {
    data.length ? exportClickFromTableId(tableId, fileName) : msgOpen("无数据可供下载，请先查询数据")
}
/**
 * 下载全部
 * @param {Array} data 导出的数据数组对象(未进行分页)
 * @param {String} fileName 需要命名的文件名
 */
const downloadExcelAll = (data, fileName) => {
    data?.forEach(item => {
        item.LAST_REDATE = dateFormat(item.LAST_REDATE)
        item.NEXT_REDATE = dateFormat(item.NEXT_REDATE)
    })
    if (data.length) {
        let newData = JSON.parse(JSON.stringify(data)) //深拷贝      
        exportClickFromDatas(newData, fileName)
    } else {
        msgOpen("无数据可供下载，请先查询数据")
    }
}

/**
 * 导入模版下载
 * @param tableId table标签的ID
 * @param fileName 需要命名的文件名
 */
const downloadTemplate = (tableId, fileName) => {
    // console.log(tableId)
    exportClickFromTableId(tableId, fileName)
}
//********************************************************************************************************************** */
//#endregion


/**
 * 处理值编辑、删除、批量操作
 * @param type 操作类型，batchDel：批量删除
 * @param data 选中的值数据
 * 
 */
const editSubmit = async (type, data) => {
    // console.log(type)
    console.log(data)
    if (type === 'add' || type === 'update' || type === 'copy') {
        updateFormRef.value.validate(async (valid) => {
            if (!valid) {
                return false
            } else {
                let res = await editLbPersonConfigInfo(type, data)
                // console.log(res)
                drawerRef.value.hideLoading()
                drawerRef.value.close()
                res.status ? msgOpen(res.msg, 'success') : msgOpen(res.msg)
                getDatas(paramsForm)
                resetForm()
            }
        })
    }
    if (type === 'delete') {
        let res = await confirm(data.ID)
        if (res) {
            let res = await editLbPersonConfigInfo(type, data)
            res.status ? msgOpen(res.msg, 'success') : msgOpen(res.msg)
            getDatas(paramsForm)
        }
    }
    if (type === 'batchAdd' || type === 'batchUpdate') {
        let rowsArr = ref([])
        let editBatchStatus = ref(true)
        for (let i = 0; i < data.length; i++) {
            console.log(data[i]);
            if(type === 'batchUpdate' && !data[i].ID){
                msgOpen("更新值，请填写ID！")
                editBatchStatus.value = false
                break
            }else if(type === 'batchAdd' && data[i].ID){
                msgOpen("新增值，ID请留空！")
                editBatchStatus.value = false
                break  
            }else {
                rowsArr.value.push(data[i])
            }
        }
        if (editBatchStatus.value) {
            let res = await editManyLbPersonConfigInfo(type, rowsArr.value)
            // console.log(res)            
            dialogRef.value.close()
            uploadTable = ref([])
            if (!res.status) {
                msgOpen(res.msg)
            } else {
                res.resDatas.result.rowsAffected ? msgOpen(`${res.msg},共${res.resDatas.result.rowsAffected}条`, "success")
                    : msgOpen(res.msg)
            }
            getDatas(paramsForm)
        }
    }
    if (type === 'batchDel') {
        if (!data.length) {
            msgOpen('未进行勾选，请勾选！')
        } else {
            let isDel = await confirmBatch(data.length)
            if (isDel) {
                let vNumArr = []
                data?.forEach(item => {
                    let arr = []
                    arr.push(item.ID)
                    vNumArr.push(arr)
                })
                let res = await editManyLbPersonConfigInfo(type, vNumArr)
                if (!res.status) {
                    msgOpen(res.msg)
                } else {
                    res.resDatas.result.rowsAffected ? msgOpen(`${res.msg},共${res.resDatas.result.rowsAffected}条`, "success")
                        : msgOpen(res.msg)
                }
                getDatas(paramsForm)
            }
        }
    }
}
//#endregion

</script>

<style lang="less" scoped>
.params-form {
    height: 100%;
    width: 100%;

    .el-form {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-start;

        .el-form-item {
            margin-bottom: 0;
            margin-right: .3125rem;
        }
    }
}

.el-table {
    height: 95%;
}

.batchChangeStatus {
    font-size: .625rem;
    margin-left: .625rem;
}

.submit-btn {
    margin-left: .625rem;
}
</style>